﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Transactions;
using System.Web;
using System.Web.Mvc;
using System.Web.Security;
using DotNetOpenAuth.AspNet;
using Microsoft.Web.WebPages.OAuth;
using WebMatrix.WebData;
using EvinceUI.Filters;
using EvinceUI.Models;
using EvincePayroll.Data;
using System.IO;
using System.Configuration;
using EvinceUI.JQueryDataTable.Model;
using EvincePayroll.Utility;
using System.Text;
using System.Drawing;

namespace EvinceUI.Controllers
{

    public class HomeController : Controller
    {
        //[Authorize]
        //public ActionResult Index()
        //{
        //    ViewBag.Message = "Modify this template to jump-start your ASP.NET MVC application.";

        //    return View();
        //}
        //[Authorize]
        //public ActionResult About()
        //{
        //    ViewBag.Message = "Your app description page.";

        //    return View();
        //}
        //[Authorize]
        //public ActionResult Contact()
        //{
        //    ViewBag.Message = "Your contact page.";

        //    return View();
        //}

        [Authorize]
        public ActionResult DashBoard()
        {
            return View();
        }
        [Authorize]
        public ActionResult Skils()
        {
            return View();
        }
        [Authorize]
        public ActionResult Gallery()
        {
            var emailId=Session["EmployeeData"] as EmployeeData;
            EvincePayrollService pageTemplateService = new EvincePayrollService(ServiceTypes.PageTemplate);
            List<GalleryData> galleryList = pageTemplateService.GetGallary(emailId.Email, true);
            return View(galleryList);
        }

        [Authorize]
        public ActionResult AddGallery()
        {
            return View();
        }
        [Authorize]
        [HttpPost]
        public ActionResult AddGallery(GalleryData gallery, HttpPostedFileBase galleryImage, string isActive)
        {
            bool result = false;
            var loginDetails = Session["EmployeeData"] as EmployeeData;
            EvincePayrollService pageTemplateService = new EvincePayrollService(ServiceTypes.PageTemplate);
            if (galleryImage != null && galleryImage.ContentLength > 0)
            {
                Guid imageId = Guid.NewGuid();
                gallery.ImageId = imageId;
                var fileName = Path.GetFileName(galleryImage.FileName);
                var path = Path.Combine(Server.MapPath("~/Images/Employee"), imageId.ToString() + "." + fileName.Split('.')[1]);
                galleryImage.SaveAs(path);
                gallery.Image = imageId.ToString() + "." + fileName.Split('.')[1];
                if (isActive == "on")
                    gallery.IsActive = 1;
                else
                    gallery.IsActive = 0;
                result = pageTemplateService.AddGalleryPage(gallery, loginDetails.Email);
            }
            ViewBag.Message = result;
            return View();
        }
        [Authorize]
        public ActionResult DeleteGalleryImage(string fileName)
        {
            bool result = false;
            EvincePayrollService pageTemplateService = new EvincePayrollService(ServiceTypes.PageTemplate);
            if (fileName != string.Empty)
            {
                var path = Path.Combine(Server.MapPath("~/Images/Employee"), fileName);
                System.IO.File.Delete(path);
                result = pageTemplateService.DeleteGalleryImage(fileName.Split('.')[0]);
                return Json(new { result }, JsonRequestBehavior.AllowGet);
            }
            return View();
        }

        public ActionResult UpdateGalleryImage(string imageId,string status)
        {
            bool result = false;
            EvincePayrollService pageTemplateService = new EvincePayrollService(ServiceTypes.PageTemplate);
            if (imageId != string.Empty)
            {
                result = pageTemplateService.UpdateGalleryImage(imageId,status);
                return Json(new { result }, JsonRequestBehavior.AllowGet);
            }
            return View();
        }

       
        public ActionResult GetGallary()
        {

            return View();
        }

        public ActionResult AjaxGetGallary(JQueryDataTableParamModel param)
        {
            List<GalleryData> galleryList;
            EmployeeData employee = (EmployeeData)Session["EmployeeData"];
            EvincePayrollService pageTemplateService = new EvincePayrollService(ServiceTypes.PageTemplate);
            galleryList = pageTemplateService.GetGallary(employee.Email,false);
            if (galleryList != null)
            {
                IEnumerable<GalleryData> filteredRequests;

                //Check whether the companies should be filtered by keyword
                if (!string.IsNullOrEmpty(param.sSearch))
                {
                    //Used if particular columns are filtered


                    var NameFilter = Convert.ToString(Request["sSearch_1"]);





                    //Optionally check whether the columns are searchable at all


                    var isNameSearchable = Convert.ToBoolean(Request["bSearchable_1"]);





                    char[] chars = new char[] { '&', '|' };

                    if (param.sSearch.IndexOfAny(chars) > 0)
                    {
                        string expression = GetExpression(param.sSearch.ToUpper());
                        StringBuilder filter = new StringBuilder();

                        filter.Append("(").Append(expression.Replace("[FIELD]", "Name.ToString().ToUpper()")).Append(")||");

                        filteredRequests = galleryList;
                    }
                    else
                    {

                        filteredRequests = galleryList
                        .Where(d => isNameSearchable && d.Name.ToLower().Contains(param.sSearch.Trim().ToLower())

                        );

                    }
                }
                else
                {
                    filteredRequests = galleryList;

                }


                var isName = Convert.ToBoolean(Request["bSortable_1"]);




                var sortColumnIndex = Convert.ToInt32(Request["iSortCol_0"]);
                Func<GalleryData, string> orderingFunction = (d => sortColumnIndex == 1 && isName ? d.Name :

                "");

                var sortDirection = Request["sSortDir_0"]; // asc or desc
                if (sortDirection == "asc")
                    filteredRequests = filteredRequests.OrderBy(orderingFunction);
                else
                    filteredRequests = filteredRequests.OrderByDescending(orderingFunction);

                var displayedCompanies = filteredRequests.Skip(param.iDisplayStart).Take(param.iDisplayLength);
                var result = from p in displayedCompanies
                             select new[] {
                                 p.ImageId.ToString(),
                                 p.Name,
                                 GetImageURL(p.Image),
                                 GetBox(p.IsActive.ToString(),p.ImageId.ToString()),
                                 getLink(p.ImageId.ToString(),p.Image)
                                 
                               
                         };

                return Json(new
                {
                    sEcho = param.sEcho,
                    iTotalRecords = galleryList.Count(),
                    iTotalDisplayRecords = filteredRequests.Count(),
                    aaData = result
                },
                JsonRequestBehavior.AllowGet);
            }
            else
                return Json(new { }, JsonRequestBehavior.AllowGet);
        }
        private string GetExpression(string p)
        {
            throw new NotImplementedException();
        }
        public string GetImageURL(string imageName)
        {
            string url=string.Empty;
            if(imageName!=null)
            {
             url= string.Format("<img src=\"../../Images/Employee/{0}\" width=\"100px\" height=\"100px\" />",imageName);
            }
            return url;
        
        }

        private string GetBox(string active,string imageId)
        {
            string url = string.Empty;
            if (active == "1")
            {

                url = string.Format("<input type=\"checkbox\" id=\"CHK{0}\" checked=\"checked\"/>",imageId);

            }
            else if (active == "0")
            {

                url = string.Format("<input type=\"checkbox\" id=\"CHK{0}\" />",imageId);


            }
            return url;

        }

        private string getLink(string link,string fileName)
        {
            string url = string.Empty;
            url = string.Format("<a href=\"#\" onclick=\"UpdateGalleryImage('{0}')\"><span>Update</span></a>&nbsp;<a href=\"#\" onclick=\"DeleteGalleryImage('{1}')\">Delete</a>", link, fileName);
            return url;



        }
    }
}
